<?php
namespace Services;

use Helpers\Tool;
use Helpers\Main;
use Helpers\HttpClient;
use Helpers\XhException;

class HundredMail {

    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;

    const DEFAULT_PATH = '/interfaces/interfaces.php';

    public static $authArr = [
        'admuser' => '',
        'admpass' => ''
    ];
    const MAIL_SUFFIX = '@100fen.cn';


    /**
     * 初始化配置
     *
     * @throws XhException
     *
     * create by dale  20181017
     */
    private static function init()
    {
        if (!self::$httpClient) {
            $config     = Main::getConfigByName('hundredMail');
            self::$url  = Tool::getValue($config, 'url');
            if (!self::$url) {
                throw new XhException('百分邮箱url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
            if (!Tool::getValue($config, 'admuser') || !Tool::getValue($config, 'admpass')) {
                throw new XhException('配置信息不完全');
            }
            self::$authArr = [
                'admuser' => base64_encode($config['admuser']),
                'admpass' => base64_encode($config['admpass'])
            ];
        }
    }

    /**
     * 百分邮件
     *
     * @param $email
     * @param string $password
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181017
     */
    public static function addMailByPhone($phone, $name = '', $password = '123456')
    {
        self::init();
        if (!$phone) {
            throw new XhException('缺少手机号');
        }

        $params = [
            'operation' => 'adduser',
            'uid' => $phone . self::MAIL_SUFFIX,
            'password' => $password,
            'telephone' => $phone
        ];
        if ($name) {
            $params['realname'] = $name;
        }
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('创建失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'EmailSever',
            'Email',
            'addEmailByPhone',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return true;
        } else {
            return $body;
        }
    }

    /**
     * 创建自定邮箱
     *
     * @param $email
     * @param string $name
     * @param string $phone
     * @param string $password
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181024
     */
    public static function addMail($email, $name = '', $phone = '', $password = '123456')
    {
        self::init();
        if (!$email) {
            throw new XhException('缺少邮箱');
        }
        $params = [
            'operation' => 'adduser',
            'uid' => $email,
            'password' => $password
        ];
        if ($name) {
            $params['realname'] = $name;
        }
        if ($phone) {
            $params['telephone'] = $phone;
        }
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('创建失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'EmailSever',
            'Email',
            'addEmail',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return true;
        } else {
            return $body;
        }
    }




    /**
     * 获取邮箱是否存在
     *
     * @param $email
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181017
     */
    public static function checkMail($email)
    {
        self::init();
        if (!$email) {
            throw new XhException('缺少邮箱地址');
        }
        $params = [
            'operation' => 'checkuserexist',
            'uid' => $email
        ];
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('获取邮箱接口调取失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'emailSever',
            'email',
            'checkEmail',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return true;
        } else {
            return $body;
        }
    }

    /**
     * 修改邮箱密码
     *
     * @param $uid
     * @param $password
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181127
     */
    public static function modifyMailPassword($uid, $password)
    {
        self::init();
        if (!$uid || !$password) {
            throw new XhException('缺少邮箱地址');
        }
        $exist = self::checkMail($uid);
        if (!$exist) {
            throw new XhException('缺少邮箱不存在');
        }
        $params = [
            'operation' => 'edituser',
            'uid' => $uid,
            'password' => $password
        ];
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('修改邮箱接口密码调取失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'emailSever',
            'email',
            'changePassword',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return true;
        } else {
            return $body;
        }
    }


    /**
     * 获取用户列表
     *
     * @param string $domain
     *
     * @return bool|array
     * @throws XhException
     *
     * create by dale  20181128
     */
    public static function getUserList($domain = '100fen.cn')
    {
        self::init();
        $params = [
            'operation' => 'getuserlist',
            'domain' => $domain,
        ];
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('获取用户列表失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'emailSever',
            'email',
            'getUserList',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return $body['user'];
        } else {
            return $body;
        }
    }

    /**
     * 获取百分邮箱信息
     *
     * @param $uid
     *
     * @return bool|mixed
     * @throws XhException
     *
     * create by dale  20181128
     */
    public static function getUserInfo($uid)
    {
        self::init();
        $params = [
            'operation' => 'userinfo',
            'uid' => $uid,
        ];
        $response = self::$httpClient->get(self::DEFAULT_PATH, array_merge($params, self::$authArr));
        if (!$response->isSuccess()) {
            throw new XhException('获取用户信息失败', $response);
        }
        $body = json_decode(json_encode((array) simplexml_load_string($response->body)), true);
        $status = strtolower(trim(Tool::getValue($body, 'status', '')));
        Main::createCommitLog(
            'emailSever',
            'email',
            'getUserInfo',
            [
                'post' => $params,
                'detail' => $body
            ],
            null,
            ''
        );
        if ($status == 'failed') {
            return false;
        } elseif ($status == 'success') {
            return $body;
        } else {
            return $body;
        }
    }



}